package org.qloudgen.borg.pages.compnent;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.validator.StringValidator;
import org.qloudgen.borg.beans.KeyValue;

@SuppressWarnings({"rawtypes", "unchecked" })
public class ParamTextField extends TextField {

	private static final long serialVersionUID = 1L;
	private List<KeyValue> validators;

	public ParamTextField(String id,IModel<String> model, List<KeyValue> validators) {
		super(id,model);
		this.validators = validators;
		addValidators();
	}

	private void addValidators(){
		
		if (this.validators == null) return;
		for (KeyValue keyValue:validators){
			
			int validatorType = Integer.valueOf(keyValue.getKey());
			String value = keyValue.getValue();

			if (StringUtils.isBlank(value)) return;
			
			IValidator validator = null;
			
			switch (validatorType) {
			
				// 位数校验
				case 1 : {
							int minimum = 0, maximum = 1;
							if (value.contains(",")) {
								String[] splits = value.split(",");
								minimum = Integer.valueOf(splits[0]);
								maximum = Integer.valueOf(splits[1]);
							} else {
								maximum = Integer.valueOf(value);
							}
							validator = StringValidator.lengthBetween(minimum, maximum);
							break;
						 }
				// 日期校验
				case 2 : {
							validator = new ParamDateValidator(value);
							break;
						 }
				// 数字检验
				case 3 : {
							validator = new ParamDigitValidator();
							break;
						 }
//				// 区间校验
//				case 4 : {
//							Float minimum = null, maximum = null;
//							
//							if (value.contains(",")) {
//								String[] splits = value.split(",");
//								if (StringUtils.isNotBlank(splits[0]))
//									minimum = Float.valueOf(splits[0]);
//								
//								if (StringUtils.isNotBlank(splits[1]))
//									maximum = Float.valueOf(splits[1]);
//							} 
//
//							validator = new RangeValidator<Float>(minimum,maximum);
//							break;
//						 }
				}
			
			if (validator != null) this.add(validator);
			
		}
		
	}
	

	protected final void onComponentTag(final ComponentTag tag)
    {
        tag.setName("input");

        super.onComponentTag(tag);
    }
}
